package com.learn.Stream;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class ForkJoinTest {
    public static final long BIG_LONG_VALUE = 10_0000_0000L;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 同时运行效率对比
         * 耗时=>734 sum=>500000000500000000
         * 耗时=>522 sum=>500000000500000000
         * 耗时=>414 sum=>500000000500000000
         */
        test1();
        test2();
        test3();
    }

    public static void test1(){
        long st = System.currentTimeMillis();
        long sum = 0l;
        for (long i = 1; i <= BIG_LONG_VALUE; i++) {
            sum += i;
        }
        long et = System.currentTimeMillis();
        System.out.println("耗时=>"+(et-st)+" sum=>"+sum);
    }

    public static void test2() throws ExecutionException, InterruptedException {
        long st = System.currentTimeMillis();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinDemo demo = new ForkJoinDemo(0L,BIG_LONG_VALUE,10000L);
        ForkJoinTask<Long> submit = pool.submit(demo);
        Long sum = submit.get();
        long et = System.currentTimeMillis();
        System.out.println("耗时=>"+(et-st)+" sum=>"+sum);
    }

    public static void test3(){
        long st = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L,BIG_LONG_VALUE).parallel().sum();
        long et = System.currentTimeMillis();
        System.out.println("耗时=>"+(et-st)+" sum=>"+sum);
    }
}
